package cn.com.miao.lynx.common.secure.filter;

import cn.com.miao.lynx.common.secure.model.AuthenticationBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * CustomLoginAuthenticationFilter
 * 登录拦截器 支持json登录
 * @title: CustomLoginAuthenticationFilter
 * @description: 登录拦截器 支持json登录
 * @author: dengmiao
 * @create: 2020-01-03 14:25
 **/
@Slf4j
public class CustomLoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //attempt Authentication when Content-Type is json
        final String contentType = request.getContentType();
        if(MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType)
                || MediaType.APPLICATION_JSON_VALUE.equals(contentType)){

            // use jackson to deserialize json
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            try (InputStream is = request.getInputStream()) {
                AuthenticationBean authenticationBean = mapper.readValue(is, AuthenticationBean.class);
                authRequest = new UsernamePasswordAuthenticationToken(
                        authenticationBean.getUsername(), authenticationBean.getPassword());
            } catch (IOException e) {
                e.printStackTrace();
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            } finally {
                assert authRequest != null;
                setDetails(request, authRequest);

            }
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        else {
            return super.attemptAuthentication(request, response);
        }
    }
}
